import cv2


# 初始化摄像头和OpenCV
def initialize_camera_and_opencv():
    cap = cv2.VideoCapture(0)  # 尝试打开摄像头，参数0代表第一个摄像头
    if not cap.isOpened():
        raise IOError("无法打开摄像头")
    return cap


# 捕获并显示视频流
def capture_and_display_video_stream(cap):
    while True:
        ret, frame = cap.read()  # 读取一帧
        if not ret:
            cap.release()  # 释放摄像头
            raise RuntimeError("无法读取摄像头帧")

        cv2.imshow('Video Stream', frame)  # 显示一帧

        if cv2.waitKey(1) & 0xFF == ord('q'):  # 如果按下'q'键，则退出循环
            break

    cap.release()  # 释放摄像头
    cv2.destroyAllWindows()  # 关闭所有OpenCV窗口


# 主函数
def main():
    try:
        cap = initialize_camera_and_opencv()
        capture_and_display_video_stream(cap)
    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == '__main__':
    main()